package com.edais.service.imp;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.edais.dao.ChannelWelfareParametersDao;
import com.edais.dao.UserChannelPointDao;
import com.edais.dao.UserDao;
import com.edais.domain.ChannelWelfareParameters;
import com.edais.domain.UserChannelPoint;
import com.edais.service.ChannelWelfareParametersService;
import com.edais.service.RateRisesCouponsService;
import com.edais.service.SMSService;
import com.edais.service.WelfareService;

@Service("channelWelfareParametersService")

public class ChannelWelfareParametersServiceImpl implements ChannelWelfareParametersService {

	private static final Log logger = LogFactory.getLog(ChannelWelfareParametersServiceImpl.class);
	
	@Autowired
	private ChannelWelfareParametersDao channelWelfareParametersDao;
	
	@Autowired
	private RateRisesCouponsService rateRisesCouponsService;
	
	@Autowired
	private SMSService sMSService;
	
	@Autowired 
	private UserChannelPointDao userChannelPointDao;
	
	@Autowired
	private UserDao usersDao;
	
	
	public void addWelfareBychannelEnName(Map<String, Object> paramsMap,HttpServletRequest request) throws Exception {
		String userId = paramsMap.get("userId").toString();
		Map<String, Object> searchMap = new HashMap<String, Object>();
		searchMap.put("userId", userId);
		//更新用户表是否已赠送注册福利字段，并判断是否已赠送
		int isGiveWelfare = usersDao.checkIsGiveWelfare(searchMap);
		if(isGiveWelfare>0){
			WebApplicationContext cont = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getSession().getServletContext());
			String channelEnName = paramsMap.get("channelEnName").toString();
			logger.info("******福利发放，查询该渠道的注册福利参数，渠道英文名："+channelEnName+",发放用户"+userId+"********");
			List<ChannelWelfareParameters> parameters = channelWelfareParametersDao.getParameterBychannelEnName(channelEnName);
			//专享加息只能赠送一次
			boolean isGiveVipIncreaseInterest=false;
			for (int i = 0; i < parameters.size(); i++) {
				if("vipInterestWelfareServiceImpl".equals(parameters.get(i).getWelfareProcessClass())){
					if(isGiveVipIncreaseInterest){
						continue;
					}
					isGiveVipIncreaseInterest=true;
				}
				WelfareService welfareService = (WelfareService) cont.getBean(parameters.get(i).getWelfareProcessClass());
				welfareService.addWelfare(parameters.get(i),paramsMap);
			}
			//若该渠道福利参数没有专享加息，则从渠道表取默认值设置
			if(!isGiveVipIncreaseInterest){
				String currentFloatRateChannel = "0";
				String fixFloatRateChannel = "0";
				String expires = "0";
				Map<String, Object>	channelInfo = usersDao.getChannelInfo(channelEnName);
				if (null == channelInfo) {
					channelInfo = this.usersDao.getChannelInfo("OTHERS");
				} else {
					currentFloatRateChannel = 
							channelInfo.get("CURRENT_FLOAT_RATE") == null ? "0" : channelInfo.get("CURRENT_FLOAT_RATE").toString();
					fixFloatRateChannel = 
							channelInfo.get("FIX_FLOAT_RATE") == null ? "0" : channelInfo.get("FIX_FLOAT_RATE").toString();
					expires = channelInfo.get("EXPIRES") == null ? "0" : channelInfo.get("EXPIRES").toString();
				}
				
				// 用户渠道等级积分表写入
				UserChannelPoint userChannelPoint = new UserChannelPoint();
				userChannelPoint.setUserId(paramsMap.get("userId").toString());
				userChannelPoint.setUserChannel(channelInfo.get("ID").toString());
				userChannelPoint.setCurrentFloatRateChannel(currentFloatRateChannel);
				userChannelPoint.setFixFloatRateChannel(fixFloatRateChannel);
				// 有效期
				if (expires == null || "".equals(expires) || "null".equals(expires)) {
					expires = "0";
				}
				if (!"0".equals(expires)) {
					SimpleDateFormat hmsFormat = new SimpleDateFormat("yyyyMMdd");
					Date date = new Date();
					String nowYmd = hmsFormat.format(date);
					Calendar cal = Calendar.getInstance();
					cal.setTime(date);
					cal.add(Calendar.DATE,Integer.parseInt(expires));
					userChannelPoint.setStartTime(nowYmd);
					userChannelPoint.setEndTime(hmsFormat.format(cal.getTime()));
				}
				userChannelPointDao.addChannelPoint(userChannelPoint);
			}
			//福利发放完毕，发送短信
			//短信开关是否开启
			String channel_register_welfare_control=rateRisesCouponsService.findParamValueByName("channel_register_welfare_control");
			if(channel_register_welfare_control==null||"".equals(channel_register_welfare_control.trim())){
				channel_register_welfare_control="0";
			}
			if("1".equals(channel_register_welfare_control)){
				try {
					sMSService.getSMS(userId, "sms06004", "",
							"");
				} catch (Exception e) {
					logger.error("发送短信异常:" + e.getMessage());
				}
			}
		}
	}

}
